<template>
  <el-dialog
    title="添加源头企业"
    :visible.sync="detailDialog"
    width="1064px"
    class="dialogTitle detailDialog"
    @closed="dialogClosed('addForm')"
  >
    <el-form label-width="225px" ref="addForm" :model="dialogData" :rules="rules">
      <el-form-item label="企业名称" class="el-form-item-text" prop="enterpriseName">
        <el-input v-model.trim="dialogData.enterpriseName"></el-input>
      </el-form-item>
      <el-form-item label="企业类型" prop="checkList">
        <el-checkbox-group v-model="dialogData.checkList">
          <el-checkbox label="国有" @change="checkboxClick('国有')"></el-checkbox>
          <el-checkbox label="集体" @change="checkboxClick('集体')"></el-checkbox>
          <el-checkbox label="股份制" @change="checkboxClick('股份制')"></el-checkbox>
          <el-checkbox label="私营" @change="checkboxClick('私营')"></el-checkbox>
          <el-checkbox label="其他" @change="checkboxClick('其他')"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="详细地址" prop="address" class="addressForm">
        <el-input v-model.trim="dialogData.address"></el-input>
        <el-button @click="addCoordinate" type="primary">添加经纬度</el-button>
        <!-- <cs-btn
          type="primary"
          @click="addCoordinate"
          btnText="添加经纬度"
          class="addCoordinateBtn"
        /> -->
      </el-form-item>
      <el-form-item label="经度" prop="longitude" class="addressForm">
        <el-input v-model.trim="dialogData.longitude" :disabled="true"></el-input>
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="dialogData.longitude = ''"
        ></el-button>
      </el-form-item>
      <el-form-item label="纬度" prop="latitude" class="addressForm">
        <el-input v-model.trim="dialogData.latitude" :disabled="true"></el-input>
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="dialogData.latitude = ''"
        ></el-button>
      </el-form-item>
      <el-form-item label="货物类型" prop="goodsType">
        <el-select
          v-model="dialogData.goodsType"
          placeholder="请选择"
          clearable
          class="form-select"
        >
          <el-option
            v-for="item in dialogData.goodsTypeOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button
          :type="isAddGoodsType ? 'danger' : 'primary'"
          class="addGoodsTypeBtn"
          @click="handleAddGoodsTypeBtnClick"
          >{{ isAddGoodsType ? '取消添加类型' : '添加货物类型' }}</el-button
        >
      </el-form-item>
      <el-form-item
        label="新增货物类型"
        prop="newGoodsType"
        :error="dialogData.newGoodsTypeErrorMsg"
        v-show="isAddGoodsType"
        class="addressForm"
      >
        <el-input v-model.trim="dialogData.newGoodsType"></el-input>
        <el-button
          type="primary"
          @click="confirmAddGoodsType"
          :loading="confirmAddGoodsTypeBtnStatus"
          >确定添加</el-button
        >
      </el-form-item>
      <el-form-item label="企业法人" prop="legalPerson">
        <el-input v-model.trim="dialogData.legalPerson"></el-input>
      </el-form-item>
      <el-form-item label="企业法人联系电话" prop="legalPersonPhone">
        <el-input v-model.trim="dialogData.legalPersonPhone"></el-input>
      </el-form-item>
      <el-form-item label="运营处责任人" prop="personLiable">
        <el-input v-model.trim="dialogData.personLiable"></el-input>
        <!-- <el-select
          v-model="dialogData.personLiable"
          placeholder="请选择"
          clearable
          class="form-select"
        >
          <el-option
            v-for="item in dialogData.personLiableOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="运营处责任人联系方式" prop="personLiablePhone">
        <el-input v-model.trim="dialogData.personLiablePhone"></el-input>
      </el-form-item>
      <el-form-item label="运营处责任人身份证号" prop="personLiableIDNumber">
        <el-input v-model.trim="dialogData.personLiableIDNumber"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model.trim="dialogData.remarks"></el-input>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <cs-btn
        type="primary"
        @click.native="confirmBtnClick('addForm')"
        btnText="确定"
        class="confirm_btn dialog_btn"
        ref="confirmBtnRef"
        :buttonStatus="confirmBtnStatus"
      />
      <cs-btn @click.native="cancelBtnClick('addForm')" btnText="取消" class="dialog_btn" />
    </div>
  </el-dialog>
</template>

<script>
import csBtn from '@/components/cs-btn/cs-btn.vue'
import {
  addEnterprise,
  isTheCompanyNameDuplicate,
  addGoodsType,
  getGoodsType
} from '@/service/source_manage/enterprise_manage'
// import { getContactsName } from '@/service/operate/user_manage/user_manage'
import { isPhoneCorrect, isIDNumberCorrect } from '@/utils/regularVerification'

export default {
  components: {
    csBtn
  },
  data() {
    // 自定义校验规则
    const isNameRepeat = async (rule, value, callback) => {
      try {
        // 查询企业名称是否重复
        const { code, data } = await isTheCompanyNameDuplicate({ companyName: value })
        if (code === 0) {
          callback()
        } else {
          callback(new Error('企业名称已存在'))
        }
      } catch (err) {
        console.log(err)
        this.$message.error('服务器出错了')
      }
    }
    const phoneCorrectVerification = async (rule, value, callback) => {
      // 验证车牌号是否正确
      if (value) {
        if (isPhoneCorrect(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的手机号'))
        }
      } else {
        callback()
      }
    }
    const IDNumberCorrectVerification = async (rule, value, callback) => {
      // 验证身份证号是否正确
      if (value) {
        if (isIDNumberCorrect(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的身份证号'))
        }
      } else {
        callback()
      }
    }
    return {
      detailDialog: false,
      checkListDefaultData: ['国有', '集体', '股份制', '私营', '其他'],
      isAddGoodsType: false,
      confirmBtnStatus: false,
      confirmAddGoodsTypeBtnStatus: false,
      dialogData: {
        enterpriseName: '',
        checkList: [],
        address: '',
        // 经度
        longitude: '',
        // 纬度
        latitude: '',
        // 货物类型
        goodsType: '',
        goodsTypeOption: [
          //   {
          //     value: 0,
          //     label: '散货'
          //   },
          //   {
          //     value: 1,
          //     label: '集装箱'
          //   },
          //   {
          //     value: 2,
          //     label: '高岭土'
          //   },
          //   {
          //     value: 3,
          //     label: '沥青'
          //   }
        ],
        // 新增货物类型
        newGoodsType: '',
        // 新增货物类型错误信息
        newGoodsTypeErrorMsg: '',
        // 企业法人
        legalPerson: '',
        // 企业法人联系电话
        legalPersonPhone: '',
        // 运营处责任人
        personLiable: '',
        // personLiableOption: [],
        // 责任人联系方式
        personLiablePhone: '',
        personLiableIDNumber: '',
        // 备注
        remarks: ''
      },
      rules: {
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
          { validator: isNameRepeat, trigger: 'blur' }
        ],
        checkList: [{ required: true, message: '请选中企业类型', trigger: 'blur' }],
        // newGoodsType: [{ required: true, message: '请输入货物类型', trigger: 'blur' }],
        // legalPerson: [{ required: true, message: '请输入企业法人名称', trigger: 'blur' }],
        legalPersonPhone: [{ validator: phoneCorrectVerification, trigger: 'blur' }],
        // personLiable: [{ required: true, message: '请输入运营处责任人名称', trigger: 'blur' }],
        personLiablePhone: [{ validator: phoneCorrectVerification, trigger: 'blur' }],
        personLiableIDNumber: [{ validator: IDNumberCorrectVerification, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.$bus.$on('addBtnClick', () => {
      this.detailDialog = true
    })
    // 查询所有运营处责任人
    // this.getContactsName()
    // this.isTheCompanyNameDuplicate({ companyName: '测试企业' })
    this.$bus.$on('confirmCoordinate', (lng, lat, address) => {
      this.dialogData.address = address
      this.dialogData.longitude = lng
      this.dialogData.latitude = lat
    })
    this.getGoodsType()
  },
  beforeDestroy() {
    this.$bus.$off('showMap_enterprise')
    this.$bus.$off('addEnterpriseSuccess')
    this.$bus.$off('addGoodsTypeSuccess')
  },
  methods: {
    addCoordinate() {
      this.$bus.$emit('showMap_enterprise', this.dialogData.address ? this.dialogData.address : '')
    },
    // 对话框关闭事件
    dialogClosed(formName) {
      this.resetForm(formName)
      this.isAddGoodsType = false
      this.dialogData.newGoodsType = ''
      this.dialogData.newGoodsTypeErrorMsg = ''
    },
    // 获取货物类型
    async getGoodsType() {
      const { code, data } = await getGoodsType()
      if (code === 0) {
        this.dialogData.goodsTypeOption = []
        data.forEach((item, index) => {
          this.dialogData.goodsTypeOption.push({ value: index, label: item })
        })
      }
    },
    // 添加货物类型按钮点击事件
    handleAddGoodsTypeBtnClick() {
      this.isAddGoodsType = !this.isAddGoodsType
      this.dialogData.newGoodsType = ''
      this.dialogData.newGoodsTypeErrorMsg = ''
    },
    // 确定添加货物类型
    async confirmAddGoodsType() {
      this.confirmAddGoodsTypeBtnStatus = true
      try {
        if (this.dialogData.newGoodsType !== '') {
          const { code, data, msg } = await addGoodsType({
            goodsType: this.dialogData.newGoodsType
          })
          console.log(data)
          if (code === 0) {
            this.getGoodsType()
            this.$bus.$emit('addGoodsTypeSuccess')
            this.$message({
              message: '添加货物类型成功',
              type: 'success'
            })
            setTimeout(() => {
              this.isAddGoodsType = false
              this.dialogData.newGoodsType = ''
              this.dialogData.newGoodsTypeErrorMsg = ''
              this.confirmAddGoodsTypeBtnStatus = false
            }, 500)
          } else {
            this.$message.error(msg)
            this.dialogData.newGoodsTypeErrorMsg = ''
            setTimeout(() => {
              this.confirmAddGoodsTypeBtnStatus = false
            }, 500)
          }
        } else if (this.dialogData.newGoodsType === '') {
          this.dialogData.newGoodsTypeErrorMsg = '货物类型不能为空'
          this.confirmAddGoodsTypeBtnStatus = false
        }
      } catch (err) {
        this.$message.error('添加货物类型失败')
        console.log(err)
        setTimeout(() => {
          this.confirmAddGoodsTypeBtnStatus = false
        }, 500)
      }
    },
    confirmBtnClick(formName) {
      // if (this.confirmBtnStatus) return
      // this.$refs.confirmBtnRef.buttonStatus = true
      this.confirmBtnStatus = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // this.confirmBtnStatus = true

          try {
            console.log(this.$refs.confirmBtnRef.buttonStatus)

            // 调用新增企业接口
            const { code, data } = await addEnterprise({
              name: this.dialogData.enterpriseName,
              type: this.checkListDefaultData.indexOf(this.dialogData.checkList[0]),
              address: this.dialogData.address,
              // 经度
              longitude: this.dialogData.longitude,
              // 纬度
              latitude: this.dialogData.latitude,
              // 货物类型
              goodsType: this.dialogData.goodsType,
              // 企业法人名称
              corporate: this.dialogData.legalPerson,
              // 企业法人电话
              corporatePhone: this.dialogData.legalPersonPhone,
              // 运营处责任人联系人名称
              contactsName: this.dialogData.personLiable,
              // 运营处责任人联系电话
              contactsPhone: this.dialogData.personLiablePhone,
              // 运营处责任人身份证号
              contactsIdCard: this.dialogData.personLiableIDNumber,
              // 备注
              remark: this.dialogData.remarks,
              // 权限ID(写死)
              permId: 133
            })
            // 如果新增企业成功
            if (code === 0) {
              this.isAddGoodsType = false
              this.dialogData.newGoodsType = ''
              this.dialogData.newGoodsTypeErrorMsg = ''
              this.$message({
                message: '添加企业成功',
                type: 'success'
              })
              this.$bus.$emit('addEnterpriseSuccess')

              this.detailDialog = false
              // this.$refs.confirmBtnRef.buttonStatus = false
              // this.confirmBtnStatus = false
              this.resetForm(formName)
            }
            setTimeout(() => {
              this.confirmBtnStatus = false
            }, 500)
          } catch (err) {
            console.log(err)
            this.$message.error('添加企业信息失败')
          }
        } else {
          // this.$refs.confirmBtnRef.buttonStatus = false
          this.confirmBtnStatus = false
        }
      })
    },
    cancelBtnClick(formName) {
      this.detailDialog = false
      this.resetForm(formName)
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 把多选框改为单选框
    checkboxClick(res) {
      this.dialogData.checkList = [res]
    }
    // 查询所有运营处责任人
    // async getContactsName() {
    //   try {
    //     const { data } = await getContactsName()
    //     if (data.code === 0) {
    //       // 遍历所有责任人数据，组成下拉框选项数据
    //       data.data.forEach((item) => {
    //         this.dialogData.personLiableOption.push({ value: item, label: item })
    //       })
    //     }
    //   } catch (err) {
    //     console.log(err)
    //     this.$message.error('服务器出错了')
    //   }
    // }
  }
}
</script>

<style scoped>
.el-form {
  margin-left: 36px;
  margin-right: 109px;
}

.el-alert {
  background-color: #fff;
  padding: 0;
  height: 24px;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-form-item >>> .el-form-item__label {
  color: #888888;
}

.detailDialog .el-form-item:first-child {
  margin-bottom: 4px;
}

.detailDialog .el-form-item:nth-child(2) {
  margin-bottom: 0;
}

.detailDialog .el-form-item:nth-child(4) {
  margin-bottom: 8px;
}
.detailDialog .el-form-item:last-child {
  margin-bottom: 68px;
}

/* checkbox样式 */
.el-checkbox >>> .el-checkbox__inner {
  border-radius: 0;
}

.el-checkbox >>> .el-checkbox__inner::after {
  top: 0;
  left: 3px;
  border: 3px solid #fff;
  border-left: 0;
  border-top: 0;
  width: 4px;
}

.el-checkbox >>> .el-checkbox__label {
  color: #606266;
}

.el-select >>> .el-input__inner {
  border-radius: 0;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
}

.el-select >>> .el-input__icon {
  line-height: 32px;
}

/* 更改el-select下拉框的图标 */
.el-select >>> .el-icon-arrow-up:before {
  content: '\e78f';
}

.form-select {
  width: 80%;
}

.addGoodsTypeBtn {
  width: 20%;
}

.selectTreeSection {
  width: 626px;
  height: 416px;
  border: 1px solid #dddddd;
  overflow: scroll;
}

.detailDialog >>> .el-dialog__header {
  padding: 32px 28px;
}

.detailDialog >>> .el-dialog__title {
  color: #006eff;
}

.detailDialog >>> .el-dialog__body {
  padding: 32px 28px 45px 28px;
}

/* 对话框关闭按钮位置 */
.detailDialog >>> .el-dialog__headerbtn {
  right: 135px;
}
/* 对话框关闭按钮大小和粗细 */
.detailDialog >>> .el-dialog__close {
  font-size: 24px;
  font-weight: 700;
}

.el-form-item >>> .el-form-item__error {
  padding-top: 2px;
}

.addressForm >>> .el-form-item__content {
  display: flex;
}

.addCoordinateBtn {
  width: 90px;
  margin-top: 3px;
  margin-left: 10px;
  margin-right: 0;
}
</style>
